package io.wmy.supex.framework.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.wmy.supex.common.consts.AppConst;
import org.apache.ibatis.executor.loader.cglib.CglibProxyFactory;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import io.wmy.supex.common.bean.SuperModel;
import io.wmy.supex.framework.support.spring.condition.DataSourceCondition;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;

@Configuration
@MapperScan(basePackages = AppConst.MAPPER_PACKAGE, annotationClass = Repository.class)
@EnableTransactionManagement(proxyTargetClass = true)
public class DBConfig {
    private static final Logger logger = LoggerFactory.getLogger(DBConfig.class);
    private static final Marker SYSTEM_MARKER = MarkerFactory.getMarker("SYSTEM");

    @Resource private DataSource dataSource;

    @Conditional(DataSourceCondition.class)
    @Bean(name = "dataSource")
    public DataSource embeddedDataSource() {
        logger.info(SYSTEM_MARKER, "嵌入式数据源初始化");
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .setScriptEncoding("UTF-8")
                .addScripts("sql/schema.sql", "sql/data.sql")
                .build();
    }

    @Conditional(DataSourceCondition.class)
    @Bean(name = "dataSource", initMethod = "init", destroyMethod = "close")
    public DataSource druidDataSource(
            @Value("${jdbc.url}") String url,
            @Value("${jdbc.url.ext}") String urlExt,
            @Value("${jdbc.username}") String username,
            @Value("${jdbc.password}") String password
    ) throws SQLException {
        logger.info(SYSTEM_MARKER, "Druid数据源初始化");
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url + urlExt);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(3);
        dataSource.setMaxActive(20);
        dataSource.setMaxWait(60000);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(30000);
        dataSource.setValidationQuery("SELECT 'x'");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnReturn(false);
        dataSource.setTestOnBorrow(false);
        dataSource.setPoolPreparedStatements(false);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(-1);
        dataSource.setFilters("stat,wall");
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws IOException {
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.getTypeAliasRegistry().registerAliases(AppConst.MODULES_PACKAGE, SuperModel.class);
        configuration.setProxyFactory(new CglibProxyFactory());
        configuration.setLogImpl(Slf4jImpl.class);

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setConfiguration(configuration);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mappers/**/*Mapper.xml"));
        return sqlSessionFactoryBean;
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
